package com.civ.sensor.dht.util;

import com.pi4j.wiringpi.Gpio;

public class DHT11 {

	public static int raspiPin = 0;
	int temperature = 0;
	int humidity = 0;

	public int getTemperature() {
		return temperature;
	}

	public void setTemperature(int temperature) {
		this.temperature = temperature;
	}

	public int getHumidity() {
		return humidity;
	}

	public void setHumidity(int humidity) {
		this.humidity = humidity;
	}

	public int DHT11_Read() {
		int t = 0, j = 0, i = 0;
		int[] buf = new int[] { 0, 0, 0, 0, 0 };
		Gpio.pinMode(raspiPin, Gpio.OUTPUT); // SET OUTPUT 引脚输出
		Gpio.pullUpDnControl(raspiPin, Gpio.PUD_DOWN); // 设置pin下拉电阻模式
		Gpio.digitalWrite(raspiPin, Gpio.LOW); // 低电平
		Gpio.delay(20); // Pull down Least 18ms
		Gpio.digitalWrite(raspiPin, Gpio.HIGH); // 高电平
		Gpio.delayMicroseconds(30); // Pull up 20~40us
		Gpio.pinMode(raspiPin, Gpio.INPUT); // SET INPUT 引脚输入

		while (Gpio.digitalRead(raspiPin) == 1 && t < 100)// DHT11 Pull down 80us
		{
			t++;
			Gpio.delayMicroseconds(1);
		}
		;
		if (t >= 100)
			return 1;
		t = 0;
		while (Gpio.digitalRead(raspiPin) != 1 && t < 100)// DHT11 Pull up 80us
		{
			t++;
			Gpio.delayMicroseconds(1);
		}
		;
		if (t >= 100)
			return 1;
		for (i = 0; i < 5; i++) {
			buf[i] = 0;
			for (j = 0; j < 8; j++) {
				buf[i] <<= 1;
				t = 0;
				while (Gpio.digitalRead(raspiPin) == 1 && t < 100) {
					t++;
					Gpio.delayMicroseconds(1);
				}
				if (t >= 100)
					return 1;
				t = 0;
				while (Gpio.digitalRead(raspiPin) != 1 && t < 100) {
					t++;
					Gpio.delayMicroseconds(1);
				}
				if (t >= 100)
					return 1;
				Gpio.delayMicroseconds(40);
				if (Gpio.digitalRead(raspiPin) == 1)
					buf[i] += 1;
			}
		}
		if (buf[0] + buf[1] + buf[2] + buf[3] != buf[4])
			return 2;
		setTemperature(buf[2]);
		setHumidity(buf[0]);
		return 0;
	}

}
